import machine
import utime as time
from machine import Pin
from machine import ADC



ai1 = ADC(machine.Pin(1)) #ai1
ai1.atten(ADC.ATTN_0DB)  #使用0衰减，精度最高，输入电压范围：0-950mv
ai2 = ADC(machine.Pin(11)) #ai2
ai2.atten(ADC.ATTN_0DB)

DI1 = machine.Pin(42, machine.Pin.IN)
DI2 = machine.Pin(41, machine.Pin.IN)

uart = machine.UART(2, baudrate=9600) #2表示485,1表示232,0表示TTL
uart.read()

def get_cfg_data(types,model):
    global senstype,sensmodel
    senstype =types
    sensmodel = model

def get_sensor_data():
    global senstype,sensmodel
    #uart485 
    # if senstype == 0:   
    if sensmodel=="UART1":
        writeBuf=bytearray([0x01,0x03,0x00,0x00,0x00,0x02,0xC4,0x0B]) 
        uart.write(writeBuf)
        time.sleep_ms(100)
        if uart.any():
            readBuf = uart.read()
            print("readBuf:", readBuf)
            humidity= ((readBuf[5] * 256) + readBuf[6])/10
            print('humidity',humidity)
            cTemp  = (readBuf[3] * 256 + readBuf[4])/10
            print('cTemp',cTemp)
            return humidity,cTemp
        else:
            return -1,-1

    #io
    # elif senstype == 1: 
    elif sensmodel=="DI1":
        value1=DI1.value()
        print("value of di1",value1)   
        return value1
        
    #adc传感器
    # elif senstype == 2: 
    elif sensmodel=="AI1":  
        val_uv_1=ai1.read_uv()
        print("value of di1",val_uv_1)   
        return val_uv_1

def get_uart_data():
    writeBuf=bytearray([0x01,0x03,0x00,0x00,0x00,0x02,0xC4,0x0B]) 
    uart.write(writeBuf)
    time.sleep_ms(100)
    if uart.any():
        readBuf = uart.read()
        print("readBuf:", readBuf)
        humidity= ((readBuf[5] * 256) + readBuf[6])/10
        print('humidity',humidity)
        cTemp  = (readBuf[3] * 256 + readBuf[4])/10
        print('cTemp',cTemp)
        return humidity,cTemp
    else:
        return -1,-1

def get_di_data():
    value1=DI1.value()
    value2=DI2.value()
    print("value of di",value1,value2)   
    return value1,value2



def get_ai_data():
    val_uv_1=ai1.read_uv()/47/1000
    val_uv_2=ai2.read_uv()/47/1000
    print("value of di1",val_uv_1,val_uv_2)   
    return val_uv_1,val_uv_2
